#!/usr/bin/env python
#coding=utf-8
import sys,os
import wx
from datetime import datetime,date,time
import time
import csv
import random

class MyDialog(wx.MessageDialog):
	def __init__(self,title,message,type):
		self.debug = True
		title = title.decode('utf-8').encode('gb2312')
		message = message.decode('utf-8').encode('gb2312')
		if (random.randint(0,10000)==0):
			message = u'双双，我爱你'
		if type=='alert':
			dlg = wx.MessageDialog(None, message,title,wx.OK)
			if dlg.ShowModal() == wx.ID_YES:
				print 'close'
			dlg.Destroy()
		elif type=='confirm':
			dlg = wx.MessageDialog(None, message,title, wx.YES_NO | wx.ICON_QUESTION)
			if dlg.ShowModal() == wx.ID_YES:
				pass
			else:
				pass
			dlg.Destroy()
		else:
			pass
class MyFrame(wx.Frame):
	def __init__(self):
		title = u'双双的小应用'
		#title = u_title.encode('utf-8')
		wx.Frame.__init__(self,None,-1,title,size=(600,400),style=wx.CAPTION|wx.CLOSE_BOX|wx.MINIMIZE_BOX|wx.SYSTEM_MENU);
		menuBar = wx.MenuBar()
		self.SetMenuBar(menuBar)
		menuFile = wx.Menu()
		menuBar.Append(menuFile, '&File')
		aboutMenu =wx.Menu()
		menuBar.Append(aboutMenu, '&about')
		#fileOpenMenuItem = menuFile.Append(-1, '&Open Image', 'Open a picture')
		#self.Bind(wx.EVT_MENU, self.OnOpen, fileOpenMenuItem)
		exitMenuItem = menuFile.Append(-1, '&Exit', 'Exit the viewer')
		self.Bind(wx.EVT_MENU, self.OnExit, exitMenuItem)
		aboutMenuItem = aboutMenu.Append(-1, '&about', 'about the app')
		self.Bind(wx.EVT_MENU, self.OnAbout, aboutMenuItem)
		self.panel = wx.Panel(self)
		self.panel.SetBackgroundColour('#FFCCFF')
		try:
			self.panel.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
			self.panel.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
		except Exception,e:
			MyDialog('提示框',str(e),'alert')
		self.button1 = wx.Button(self.panel,label=u'请选择所有孩子文件',pos=(100,50))
		self.textContrl1 = wx.TextCtrl(self.panel,wx.NewId(),'',pos=(250,50),size=(280,25),style=wx.TE_READONLY)
		self.button2 = wx.Button(self.panel,label=u'请选择男孩对照文件',pos=(100,100))
		self.textContrl2 = wx.TextCtrl(self.panel,wx.NewId(),'',pos=(250,100),size=(280,25),style=wx.TE_READONLY)
		self.button3 = wx.Button(self.panel,label=u'请选择女孩对照文件',pos=(100,150))
		self.textContrl3 = wx.TextCtrl(self.panel,wx.NewId(),'',pos=(250,150),size=(280,25),style=wx.TE_READONLY)
		self.button4 = wx.Button(self.panel,label=u'生成结果',pos=(200,220),size=(100,40))



		self.Bind(wx.EVT_BUTTON, self.OnButtonClick1, self.button1)
		self.Bind(wx.EVT_BUTTON, self.OnButtonClick2, self.button2)
		self.Bind(wx.EVT_BUTTON, self.OnButtonClick3, self.button3)
		self.Bind(wx.EVT_BUTTON, self.OnButtonClick4, self.button4)

		
	def OnEraseBackground(self,event):
		dc = event.GetDC()
		if not dc:
			dc = wx.ClientDC(self)
			rect = self.GetUpdateRegion().GetBox()
			dc.SetClippingRect(rect)
		dc.Clear()
		num = str(random.randint(1,2))
		if(not os.path.isfile(sys.path[0]+"\\resource\\"+num+".jpg")):
			num = '1'
		bmp = wx.Bitmap(sys.path[0]+"\\resource\\"+num+".jpg")
		dc.DrawBitmap(bmp,0,0)

	def OnButtonClick1(self,event):
		fd = wx.FileDialog(self, message=u"请选择文件", defaultDir=os.getcwd(),defaultFile="", style=wx.OPEN)
		if fd.ShowModal() == wx.ID_OK:
			filepath = fd.GetPath()
			self.textContrl1.SetValue(filepath);
			fd.Destroy()
			event.Skip()
	def OnButtonClick2(self,event):
		fd = wx.FileDialog(self, message=u"请选择文件", defaultDir=os.getcwd(),defaultFile="", style=wx.OPEN)
		if fd.ShowModal() == wx.ID_OK:
			filepath = fd.GetPath()
			self.textContrl2.SetValue(filepath);
			fd.Destroy()
			event.Skip()
	def OnButtonClick3(self,event):
		fd = wx.FileDialog(self, message=u"请选择文件", defaultDir=os.getcwd(),defaultFile="", style=wx.OPEN)
		if fd.ShowModal() == wx.ID_OK:
			filepath = fd.GetPath()
			self.textContrl3.SetValue(filepath);
			fd.Destroy()
			event.Skip()
	def OnButtonClick4(self,event):
		path1 = self.textContrl1.GetValue()
		path2 = self.textContrl2.GetValue()
		path3 = self.textContrl3.GetValue()
		if(not os.path.isfile(path1) or not os.path.isfile(path2) or not os.path.isfile(path3)):
			MyDialog('提示框','三个文件都要选择哦','alert')
			return False
		if(self.GetFileExt(path1)!='csv' or self.GetFileExt(path2)!='csv' or self.GetFileExt(path3)!='csv'):
			MyDialog('提示框','三个文件必须都是csv文件哦','alert')
			return False
		path4 = self.CreateFile(path1,path2,path3)
		if(path4):
			text =wx.StaticText(self.panel,-1,u'生成成功！！！文件地址为：'+path4,pos=(100,280),size=(450,50))
			#text.SetForegroundColour('black')
			#text.SetBackgroundColour('white')
		event.Skip()

	def CreateFile(self,path1,path2,path3):
		dt = datetime.now()
		fileName = self.GetFileName(path1)+'_'+dt.strftime('%Y%m%d%H%M%S')
		path4 = os.getcwd()+'\\'+fileName+'.csv'
		file1 = open(path1,'rb')
		file2 = open(path2,'rb')
		file3 = open(path3,'rb')
		content1 =list(csv.reader(file1))
		content2 =list(csv.reader(file2))
		content3 =list(csv.reader(file3))
		
		content1 = map(self.data2utf8,content1)
		#self.VarDump(content1);
		if(content1[2] !=['序号','姓名','性别','出生年月','实足年龄','身长cm','评定','体重kg','评定','特殊儿童评定']):
			MyDialog('提示框','孩子文件格式不对哦','alert')
			return False
		data = []
		data.append(['序号','姓名','性别','身高指标','体重指标'])
		try:
			for k in range(len(content1)):
				if(k<=2 or content1[k][1]==''):
					continue
				name = content1[k][0]
				sex = content1[k][1]
				age = float(content1[k][2])
				height = float(content1[k][3])
				weight = float(content1[k][4])
				if(content1[k][2]=='男'):
					content4 = content2
				else:
					content4 = content3
				for k1 in range(len(content4)):
					if(k1==0):
						continue
					if(age>float(content4[k1][0]) and float(content4[k1+1][0])>age):
						#print age,content4[k1][0],content4[k1+1][0],weight,content4[k1][1],content4[k1][-1],content4[0][-1]
						if(weight<float(content4[k1][1])):
							data.append([name,sex,content4[0][1]+'~'+content4[0][1]])
						elif(weight>float(content4[k1][-1])):
							data.append([name,sex,content4[0][-1]+'~'+content4[0][-1]])
						else:
							for k2 in range(len(content4[k1])):
								if(weight>float(content4[k1][k2]) and weight<float(content4[k1][k2+1])):
									data.append([name,sex,content4[0][k2]+'~'+content4[0][k2+1]])
									break
						break


		except Exception,e:
			MyDialog('提示框',str(e),'alert')
			return False
		#return path4
		#创建一个目标文件
		file4 = open(path4,'wb');
		cw = csv.writer(file4,quoting=csv.QUOTE_ALL)
		data = map(self.data2gbk,data)
		cw.writerows(data)
		file1.close()
		file2.close()
		file3.close()
		file4.close()
		return path4
	def GetFileName(self,path):
		name =path.split('.')[-2].split('\\')[-1]
		return name
	def GetFileExt(self,path):
		ext = path.split('.')[-1]
		return ext

	def data2gbk(self,data):
		if isinstance(data,str):
			return data.decode('utf-8').encode('gb2312')
		elif isinstance(data,list):
			rs = []
			for v in data:
				if isinstance(v,str):
					rs.append(v.decode('utf-8').encode('gb2312'))
				else:
					rs.append(v)
			return rs
		else:
			return False
	def data2utf8(self,data):
		if isinstance(data,str):
			return data.decode('gb2312').encode('utf-8')
		elif isinstance(data,list):
			rs = []
			for v in data:
				if isinstance(v,str):
					rs.append(v.decode('gb2312').encode('utf-8'))
				else:
					rs.append(v)
			return rs
		else:
			return False
	def VarDump(self,data):
		if (isinstance(data,list) or isinstance(data,tuple)):
			for v in data:
				print v
		else:
			print data
	def OnOpen(self,event):
		file_dialog = wx.FileDialog(self, message=u"请选择文件", defaultDir=os.getcwd(),defaultFile="", style=wx.OPEN)

	def OnExit(self,event):
		self.Destroy()
	def OnAbout(self,event):
		MyDialog('about','This is a funny App just for lovely shuangshuang','alert')
class MyApp(wx.App):
	def OnInit(self):
		self.frame = MyFrame()
		self.frame.Center()
		self.frame.Show()
		self.SetTopWindow(self.frame)	
		return True

if __name__ == '__main__':
	app = MyApp()
	app.MainLoop()
